# coding: UTF-8
# Filename : user_api.py
# Company : imedia
# Author : rose
# -*-coding:utf-8 -*-
from api.common.common import *
from api.common import mysql,log,utils,httputils
import time
import user_data_model
import traceback
import urllib2
import cPickle as p
import user_manage
'''
http://api.imedia.com/app/user/register
'''
switchlistfile = utils.readFromIni('info_data_path')
#做严格验证
def valitade(cus_id, mobile, pwd, pwd2):
    flag = True
    msg = ''
    if not utils.is_num(mobile) or not len(mobile) == 11 or not utils.regex('^1[3|4|5|8]\d{9}$', mobile): 
        flag = False
        msg += '手机号码不正确'
    if pwd ==None or pwd.strip() == '' or pwd2 == None or pwd2.strip() == '':
        flag = False
        msg += '密码为空或不相等'
    if pwd.strip() != pwd2.strip():
        flag = False
        msg += '两次输入密码不相等'
    if not utils.is_num(cus_id): 
        flag = False
        msg += '用户id不为整数'
    sql = '''select count(tb1.id) from `user` tb1, `user_cus_list` tb2 
    where tb1.id = tb2.user_id
    and tb1.username = %s
    and tb2.cus_id = %s
    '''
    rst = mysql.get(sql, [mobile, cus_id])
    if rst[0] != 0:
        flag = False
        msg += '该手机号已存在'
    return (flag, msg)

#获取省份和城市
def get_pro_city(mobile):
    sql = '''
        select province_id, city_id from phone 
        where telstr = %s
    '''
    telstr = mobile[0:7]
    rst = mysql.get(sql,[telstr])
    province_id = 0
    city_id = 0
    if rst != None and len(rst) > 0:
        province_id = rst[0]
        city_id = rst[1]
    return (province_id, city_id)   

#插入user
def insert_into_user(mobile, province_id, city_id, nowtime):
    sql_insert = '''
        insert into `user` 
        (username, reg_time, last_time, province_id, city_id) 
        values (%s, %s, %s, %s, %s) '''
    mobile_int = int(mobile)
    province_id_int = int(province_id)
    city_id_int = int(city_id)
    param_insert = [mobile_int, nowtime, nowtime, province_id_int, city_id_int]
    result = mysql.insert(sql_insert, param_insert)
    return result

#插入user_cus_list
def insert_into_user_cus_list(user_id, cus_id, pwd, now_time):
    sql_insert_ucl = '''
                    insert into user_cus_list
                    (user_id, cus_id, password, reg_time) 
                    values(%s, %s, %s, %s)
                '''
    param_insert_ucl = [user_id, int(cus_id), utils.getMD5(pwd), now_time]
    result = mysql.insert(sql_insert_ucl, param_insert_ucl)
    return result
    
#根据手机号码获取user主键
def get_user_id(mobile, cus_id):
    mobile_int = int(mobile)
    sql_select = '''select max(id) from `user`
    where username = %s
    '''
    user_obj = mysql.get(sql_select, [mobile_int])
    user_id = user_obj[0]    
    return user_id

#注册业务(action 入口)
def register(request):
    httputils.footprint(request)
    #通信验证
    if validate(request):
        return validate(request)
    
    #注册信息验证
    cus_id = httputils.post(request, 'cus_id')
    mobile = httputils.post(request, 'mobile')
    pwd = httputils.post(request, 'pwd')
    pwd2 = httputils.post(request, 'pwd2')
    info = valitade(cus_id, mobile, pwd, pwd2)
    if not info[0]:
        error_info = user_data_model.error_model
        error_info = error_info.replace('{code}', '105')
        error_info = error_info.replace('{msg}', info[1])
        log.print_error_log('warning:user_api.py->method_register验证失败')
        return response(error_info)
    
    
    #----------------------------以下做注册----------------------------
    pro_city = get_pro_city(mobile)
    user_id = 0
    now_time_int = 0
    try:
        #插入user表
        now_time = time.time()
        now_time_int = int(now_time)
        insert_result = insert_into_user(mobile, pro_city[0], pro_city[1], now_time_int)
        
        #查找刚刚主键
        user_id = get_user_id(mobile, cus_id)
        if insert_result:
            try:
                #插入user_cus_list表
                insert_result_ucl = insert_into_user_cus_list(user_id, cus_id, pwd, now_time_int)
                if insert_result_ucl:
                    #调用直接生成会员接口
                    is_reg_member = user_manage.reg_member(user_id, cus_id, mobile)
                    success = user_data_model.imedia_body
                    success = success.replace('{uid}', str(user_id)).replace('{success}', str(is_reg_member))
                    return response(success)
                else:
                    mysql.delete('delete from `user` where id = %s' % user_id)
                    mysql.delete('delete from user_cus_list where user_id = %s' % user_id)
                    error_info = user_data_model.error_model
                    error_info = error_info.replace('{code}', '106')
                    error_info = error_info.replace('{msg}', 'user_cus_list插入失败')
                    log.print_error_log('warning:user_api.py->method_register_user_cus_list插入失败')
                    return response(error_info)
            except:
                mysql.delete('delete from `user` where id = %s' % user_id)
                mysql.delete('delete from user_cus_list where user_id = %s' % user_id)
                log.print_error_log('exception:mysql.py->method_register_user_cus_list_插入异常_'+str(traceback.format_exc()).replace('\n\r',''))
                error_info = user_data_model.error_model
                error_info = error_info.replace('{code}', '106')
                error_info = error_info.replace('{msg}', 'user_cus_list插入异常')
                return response(error_info)
                
        else:
            mysql.delete('delete from `user` where id = %s' % user_id)
            mysql.delete('delete from user_cus_list where user_id = %s' % user_id)
            error_info = user_data_model.error_model
            error_info = error_info.replace('{code}', '106')
            error_info = error_info.replace('{msg}', 'user插入失败')
            log.print_error_log('warning:user_api.py->method_register_user_cus_list插入失败')
            return response(error_info)
    except:
        mysql.delete('delete from `user` where id = %s' % user_id)
        mysql.delete('delete from user_cus_list where user_id = %s' % user_id)
        log.print_error_log('exception:mysql.py->method_register_user_插入异常_'+str(traceback.format_exc()).replace('\n\r',''))
        error_info = user_data_model.error_model
        error_info = error_info.replace('{code}', '106')
        error_info = error_info.replace('{msg}', 'user插入异常')
        return response(error_info)

#判断是否为空
def is_full(obj):
    return obj != None and str(obj).strip() != ''

#得到用户id
def get_user_id_by_pwd(mobile, pwd, cus_id):
    sql = '''
    select tb1.id from `user` tb1, user_cus_list tb2
    where tb1.id = tb2.user_id
    and tb1.active = '1'
    and tb1.username = %s
    and tb2.password = %s
    and tb2.cus_id = %s
    '''
    mobile_int = int(mobile)
    md5_pwd = utils.getMD5(pwd)
    param = [mobile_int, md5_pwd, cus_id]
    user_obj = mysql.get(sql, param)
    user_id = 0
    if user_obj != None and len(user_obj) != 0:
        user_id = user_obj[0]
    return user_id

#找回密码验证函数
def check_pwd(objs):
    msg = ''
    flag = True
    user_id = 0
    if not utils.is_num(objs[0]) or not len(objs[0]) == 11 or not utils.regex('^1[3|4|5|8]\d{9}$', objs[0]): 
        flag = False
        msg = '手机号码格式不正确'    
    #信息验证
    if is_full(objs[0]) and is_full(objs[1]) and is_full(objs[2]) and is_full(objs[3]):
        if objs[2] != objs[3]:
            flag = False
            msg += '两次输入密码不一致'
        
        user_id = get_user_id_by_pwd(objs[0], objs[1], objs[4]);
        if user_id == 0:
            flag = False
            msg += '用户名密码不正确'
    else:
        flag = False
        msg += '密码或重复密码为空'
    
    return (flag, msg, user_id)


#修改密码action入口
def change_pwd(request):
    httputils.footprint(request)
    #通信验证
    if validate(request):
        return validate(request)
    
    mobile = httputils.post(request, 'mobile')
    cus_id = httputils.post(request, 'cus_id')
    old_pwd = httputils.post(request, 'old_pwd')
    new_pwd = httputils.post(request, 'new_pwd')
    re_new_pwd = httputils.post(request, 're_new_pwd')
    if not utils.is_num(cus_id): cus_id = 0
    info = check_pwd((mobile, old_pwd, new_pwd, re_new_pwd, cus_id))
    if not info[0]:
        error_info = user_data_model.error_model.replace('{msg}', info[1])
        log.print_error_log('warning:user_api.py->method_change_pwd验证失败')
        return response(error_info)
    else:
        sql = '''update  user_cus_list tb1
                set tb1.password = %s
                where tb1.user_id in (select tb2.id  from `user` tb2 where tb2.username = %s)
                and tb1.cus_id = %s
                 '''
        mobile_int = int(mobile)
        md5_pwd = utils.getMD5(new_pwd)
        param = [md5_pwd, mobile_int, cus_id]
        
        rst = mysql.update(sql, param)
        if rst:
            user_id_str = str(info[2])
            success = user_data_model.imedia_body
            success = success.replace('{uid}', user_id_str).replace('{success}', '1')
            return response(success)
        else:
            error_info = user_data_model.error_model.replace('{msg}', '修改密码失败')
            return response(error_info)

#存储对象到文件
def store_obj(obj):
    f = file(switchlistfile, 'w')
    p.dump(obj, f)
    f.close()
#获得存储文件中数据
def get_obj():
    f = file(switchlistfile)
    obj = p.load(f)
    f.close()
    return obj

#检查获取密码时间
def check_is_get_pwd(mobile, cus_id):
    flag = True
    key_value = mobile+cus_id
    #时间间隔3600秒
    time_limit_allowed = 3600
    obj = get_obj()
    now = int(time.time())
    if isinstance(obj, dict):
        if obj.has_key(key_value):
            last_time = obj[key_value]
            time_limit =  now - last_time
            #间隔时间小于time_limit_allowed秒时候禁止发送
            if time_limit < time_limit_allowed:
                flag = False
            else:
                obj[key_value] = now
                store_obj(obj)
        else:
            obj[key_value] = now
            store_obj(obj)
    return flag
    

#找回密码action入口
def find_pwd(request):
    httputils.footprint(request)
    #通信验证
    if validate(request):
        return validate(request)
        
    mobile = httputils.post(request, 'mobile')
    cus_id = httputils.post(request, 'cus_id')
    if not utils.is_num(cus_id): cus_id = 0
    
    if not utils.is_num(mobile) or not len(mobile) == 11 or not utils.regex('^1[3|4|5|8]\d{9}$', mobile): 
        msg = '手机号码格式不正确'
        error_info = user_data_model.error_model.replace('{msg}', msg)
        return response(error_info)
    
    sql = '''select tb2.password, tb1.id  from `user` tb1, user_cus_list tb2
            where tb1.id = tb2.user_id
            and tb1.username = %s
            and tb2.cus_id = %s
            '''
    mobile_int = int(mobile)
    param = [mobile_int, int(cus_id)]       
    obj = mysql.get(sql, param)
    if obj != None and len(obj) != 0:
        
        if not check_is_get_pwd(str(mobile), str(cus_id)):
            msg = '密码已经发送至您手机,请过一个小时再试'
            error_info = user_data_model.error_model_106.replace('{msg}', msg)
            return response(error_info)
        
        #更新密码
        pwd = utils.get_random_str(6)
        sql = '''update  user_cus_list tb1
                set tb1.password = %s
                where tb1.user_id in (select tb2.id  from `user` tb2 where tb2.username = %s) 
                and tb1.cus_id = %s
                '''
        mobile_int = int(mobile)
        md5_pwd = utils.getMD5(pwd)
        param = [md5_pwd, mobile_int, cus_id]
        update_rst = mysql.update(sql, param)
        
        #数据库更新成功则做信息发送逻辑
        if update_rst:
            content = user_data_model.phone_msg_model % (mobile, pwd)
            url = user_data_model.url_model % (mobile, content)
            rst = urllib2.urlopen(url).read()
            if rst == '发送成功':
                uid = obj[1]
                user_id_str = str(uid)
                success = user_data_model.imedia_body
                success = success.replace('{uid}', user_id_str).replace('{success}', '1')
                return response(success)
            else:
                msg = str(rst)
                error_info = user_data_model.error_model.replace('{msg}', msg)
                return response(error_info)
        else:
            msg = '数据库更新失败'
            error_info = user_data_model.error_model.replace('{msg}', msg)
            return response(error_info)
    else:
        msg = '您的手机号码有误'
        error_info = user_data_model.error_model.replace('{msg}', msg)
        return response(error_info)
        
            
